package com.flappySeeker.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.lilystudio.smarty4j.Context;
import org.lilystudio.smarty4j.Engine;
import org.lilystudio.smarty4j.Template;
import org.lilystudio.smarty4j.TemplateException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flappySeeker.controller.Constants;


public class SmartyManager {
/*	public final static String INITPARAM_TEMPLATE_PATH = "D:/a";	//模板引擎包路径
	public final static String TEMPLATE_ST="/temp.st";//数据模板
*/	
	public final static String INITPARAM_TEMPLATE_PATH = "/com/flappySeeker/template";	//模板引擎包路径
	public final static String TEMPLATE_ST="/temp.st";//数据模板
	public final static String RESULT_PATH ="/WebContent/xstory";//结果数据文件夹
		
	public static final String CONFIG_SERVLET_CONTEXT_KEY = "smarty.engine";
	public static SmartyManager smartyManager=null;
	public SmartyManager() {
		super();
	}
	protected String templatePath; //模板路径
	protected Engine engine =new Engine();
	public void setEngine(Engine engine) {
		this.engine = engine;
	}
	
	public  Engine getEngine(){
		return engine;
	}
	public static SmartyManager getInstance() {
	       if (smartyManager == null) {
	    	   smartyManager = new SmartyManager();
	       }
	       return smartyManager;
	    }
	/**
	 * @param obj 参数对象  map
	 * @param path	模板路径,String path
	 * @param contextname 放入context名字 
	 * @return ByteArrayOutputStream
	 */
	public static  ByteArrayOutputStream templateout(Map<String, Object> map){
		try {
			Context context = new Context(); // 生成数据容器对象
			//这里需要设置数据的值
			Set<String> set =map.keySet();
			for (String key : set) {
				Object value = map.get(key);
				if(value!=null){
					context.set(key,value );
				}
			}
			Engine engine = new Engine();
			engine.setEncoding(Constants.ENCODING_UTF8);
			engine.setTemplatePath(SmartyManager.class.getClassLoader().getResource(INITPARAM_TEMPLATE_PATH).getPath() );
			ByteArrayOutputStream out = new ByteArrayOutputStream(); //设置接收模板数据的输出流
			Template temp =engine.getTemplate(TEMPLATE_ST);
			temp.merge(context, out);
			return out;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
	public static void main(String[] args) throws Exception, TemplateException {
		Map<String, Object> map= new HashMap<String, Object>();
		map.put("name", "ddddddddddddd");
	}
	
}
